<template>
  <div class="h-100 flex">
    <div class="page-box box-1 flex-column">
      <div class="btns-line">
        <el-button
          type="primary"
          icon="el-icon-plus"
          @click="showAddDictionaryType"
          >新增字典</el-button
        >
      </div>
      <div class="flex-1 flow-y-auto">
        <data-table
          ref="table"
          :rowClick="currentChange"
          :pageObj="params"
          @modifyItem="modifyItem"
          @deleteItem="deleteItem"
          element-loading-text="加载中..."
          height="580"
          v-bind="tableOptions"
          v-loading="tableLoading"
          :updateCallback="getDataDicList"
        ></data-table>
      </div>
    </div>
    <div class="page-box flex-1 flex-column">
      <div class="btns-line">
        <el-button type="danger" icon="el-icon-delete" :disabled="!canClickDelOption" @click="delOptions"
          >批量删除</el-button
        >
        <el-button type="primary" icon="el-icon-plus" @click="addOption" :disabled="tableOptions.tableData.length === 0"
          >新建选项</el-button
        >
      </div>
      <div class="options-box flex-1 flow-y-auto" v-loading="optionTableLoading">
        <el-row class="option-row options-header">
          <el-col :span="9" :offset="2">
            选项名称
          </el-col>
          <el-col :span="9">
            选项值
          </el-col>
          <el-col :span="4">
            操作
          </el-col>
        </el-row>
        <el-row class="option-row" v-for="(item, index) in optionsList">
          <el-col :span="2" class="pl-5 pr-5 show-text">
            <el-checkbox v-model="item.isChecked"></el-checkbox>
          </el-col>
          <el-col :span="16">
            <el-form
              v-if="item.isEditing"
              ref="optionForm"
              :model="optionForm"
              :rules="optionRules"
            >
              <el-row>
                <el-col :span="12" class="pl-5 pr-5">
                  <el-form-item prop="dicTagName">
                    <el-input
                      v-model="optionForm.dicTagName"
                      placeholder="请输入选项名称"
                    ></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12" class="pl-5 pr-5">
                  <el-form-item prop="tagValue">
                    <el-input
                      v-model="optionForm.tagValue"
                      placeholder="请输入选项值"
                    ></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
            <el-row v-else class="show-text">
              <el-col :span="12" class="pl-5 pr-5 text-overflow">
                {{ item.dicTagName }}
              </el-col>
              <el-col :span="12" class="pl-5 pr-5 text-overflow">
                {{ item.tagValue }}
              </el-col>
            </el-row>
          </el-col>
          <el-col :span="5" class="pl-5 pr-5">
            <el-button
              v-if="item.isEditing"
              type="primary"
              @click="saveOptionItem(item)"
              style="margin: 0px;"
              >保存</el-button
            >
            <el-button
              v-if="item.isEditing"
              @click="cancelSaveOptionItem(item)"
              style="margin: 0px;"
              >取消</el-button
            >
            <el-button v-if="!item.isEditing" @click="editOptionItem(item)">编辑</el-button>
          </el-col>
        </el-row>
      </div>
    </div>
    <el-dialog
      :visible.sync="dictionaryTypeVisible"
      :title="dialogTitle"
      :close-on-click-modal="false"
      @close="dialogClose('dictionaryType')"
      custom-class="selfDialog"
      width="500px"
      v-loading="dialogLoading"
    >
      <el-form ref="typeForm" :model="typeForm" label-width="80px">
        <el-form-item
          prop="dataDicName"
          label="名称"
          :rules="rules.dataDicName"
        >
          <el-input
            v-model="typeForm.dataDicName"
            placeholder="请输入名称"
          ></el-input>
        </el-form-item>
        <el-form-item
          prop="description"
          label="描述"
          :rules="rules.description"
        >
          <el-input
            v-model="typeForm.description"
            placeholder="请输入描述"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dictionaryTypeVisible = false" size="mini"
          >取消</el-button
        >
        <el-button @click="subForm('dictionaryType')" size="mini" type="primary"
          >确定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { confirm } from "@/utils/tools";
import { getDataDicList, setDataDic, getDataDicItem, delDataDicItem } from "@/api/formApi";
import { validateIllegality, validateEnNumber } from "@/utils/validate";

export default {
  name: "dictionaryManage",
  data() {
    return {
      params: {
        page: 1,
        size: 10,
        factoryId: window.localStorage.factoryId,
        dicTypeName: null,
        total: 0
      },
      tableOptions: {
        tableData: [],
        modifySettings: [
          {
            eventName: "modifyItem",
            name: "编辑",
            btnType: "",
            code: "mes-systemConfig-middleWare-btn_edit"
          },
          {
            eventName: "deleteItem",
            name: "删除",
            btnType: "danger",
            code: "mes-systemConfig-middleWare-btn_edit"
          }
        ],
        _columns: [
          {
            prop: "dataDicName",
            label: "字典名称"
          },
          {
            prop: "description",
            label: "字典描述"
          }
        ]
      },
      optionsList: [],
      typeForm: {
        dataDicName: null,
        factoryId: window.localStorage.factoryId,
        description: null
      },
      rules: {
        dataDicName: [
          {
            required: true,
            min: 1,
            max: 64,
            message: "请输入64个字符以内的名称",
            trigger: "blur"
          },
          { validator: validateIllegality, trigger: "blur" }
        ],
        description: {
          min: 0,
          max: 256,
          message: "请输入256个字符以内的描述",
          trigger: "blur"
        }
      },
      optionTableLoading: false,
      tableLoading: false,
      dictionaryTypeVisible: false,
      dialogTitle: null,
      isEdit: false,
      currentItem: {},
      optionForm: {
        dicTagName: null,
        tagValue: null
      },
      optionRules: {
        dicTagName: [
          {
            required: true,
            min: 1,
            max: 16,
            message: "请输入16个字符以内的名称",
            trigger: "blur"
          },
          { validator: validateIllegality, trigger: "blur" }
        ],
        tagValue: [
          {
            required: true,
            min: 1,
            max: 32,
            message: "请输入32个字符以内的值",
            trigger: "blur"
          },
          { validator: validateEnNumber, trigger: "blur" }
        ]
      },
      dialogLoading: false
    };
  },
  created() {
    this.getDataDicList();
  },
  computed: {
    canClickDelOption() {
      return this.optionsList.some(item => item.isChecked === true)
    }
  },
  methods: {
    getDataDicList() {
      this.tableLoading = true;
      getDataDicList(this.params).then(res => {
        this.tableLoading = false;
        if (res.data.rows) {
          this.tableOptions.tableData = res.data.rows;
          this.params.total = res.data.total;
          if (res.data.rows.length === 0 && res.data.total !== 0) {
            this.params.page--;
            this.getDataDicList();
            return;
          }
          if (res.data.rows.length > 0) {
            this.$nextTick(() => {
              this.$refs.table.setCurrentRow(res.data.rows[0]);
              this.currentItem = res.data.rows[0];
              this.getDataDicItem();
            });
          }
        }
      }).catch(err => {
        this.tableLoading = false
      })
    },
    getDataDicItem() {
      this.optionTableLoading = true;
      getDataDicItem({ dataDicId: this.currentItem.dataDicId }).then(res => {
        this.optionTableLoading = false;
        this.optionsList = res.data || [];
        this.optionsList.forEach(item => {
          this.$set(item, "isChecked", false);
          this.$set(item, "isEditing", false);
        });
      });
    },
    modifyItem(item) {
      if (this.isEditingOption()) {
        this.$message("请先保存正在编辑的选项!");
        return;
      }
      this.dialogTitle = "编辑字典";
      this.typeForm = Object.assign({}, item)
      this.dictionaryTypeVisible = true;
      this.isEdit = true;
    },
    deleteItem(item) {
      if (this.isEditingOption()) {
        this.$message("请先保存正在编辑的选项!");
        return;
      }
      confirm("删除之后不可撤销，是否确定？").then(res => {
        delDataDicItem({ dataDicId: item.dataDicId }).then(res => {
          this.$message({
            type: "success",
            message: "删除成功"
          })
          this.optionsList = []
          this.getDataDicList();
        });
      });
    },
    showAddDictionaryType() {
      if (this.isEditingOption()) {
        this.$message("请先保存正在编辑的选项!");
        return;
      }
      this.dictionaryTypeVisible = true;
      this.dialogTitle = "新增字典";
      this.isEdit = false;
    },
    subForm(type) {
      this.$refs.typeForm.validate(valid => {
        if (valid) {
          this.dialogLoading = true
          this.submitTypeForm();
        } else {
          return false;
        }
      })
    },
    submitTypeForm() {
      this.typeForm.factoryId = window.localStorage.factoryId
      setDataDic(this.typeForm).then(res => {
        this.dictionaryTypeVisible = false;
        this.getDataDicList();
      }).catch(err => {
        this.dialogLoading = false
      });
    },
    dialogClose(type) {
      this.dialogLoading = false
      this.typeForm.dataDicName = null;
      this.typeForm.description = null;
      this.$refs.typeForm.resetFields();
    },
    currentChange(item) {
      this.currentItem = item;
      this.getDataDicItem();
    },
    delOptions() {
      confirm("删除之后不可撤销，是否确定？").then(res => {
        let _optionList = this.optionsList.concat([])
        this.optionsList = this.optionsList.filter(item => item.isChecked === false)
        const errorCallback = () => {
          this.optionsList = _optionList
        }
        const successCallback = () => {}
        this.subOptions(successCallback, errorCallback)
      });

    },
    addOption() {
      if (this.isEditingOption()) {
        this.$message("请先保存正在编辑的选项!");
        return;
      }
      this.optionForm = {
        dicTypeName: null,
        tagValue: null
      };
      this.optionsList.unshift({
        dicTagName: null,
        tagValue: null,
        isEditing: true,
        isChecked: false,
        isNewTag: true
      });
    },
    isEditingOption() {
      return this.optionsList.some(item => item.isEditing === true);
    },
    editOptionItem(item) {
      if (this.isEditingOption()) {
        this.$message("请先保存正在编辑的选项!");
        return;
      }
      this.optionForm = {
        dicTagName: item.dicTagName,
        tagValue: item.tagValue
      }
      this.$set(item, 'isEditing', true)
    },
    saveOptionItem(item) {
      this.$refs.optionForm[0].validate(valid => {
        if (valid) {
          let _item = Object.assign({}, item)

          const errorCallback = () => {
            if (_item.dicTagName === null && _item.tagValue === null) {
              this.optionsList.pop()
            }else{
              this.$set(item, "dicTagName", _item.dicTagName);
              this.$set(item, "tagValue", _item.tagValue);
            }
            this.$forceUpdate()
          }
          const successCallback = () => {
            this.$set(item, "isEditing", false);
            this.clearOptionForm();
          }

          this.$set(item, "dicTagName", this.optionForm.dicTagName);
          this.$set(item, "tagValue", this.optionForm.tagValue);
          this.subOptions(successCallback, errorCallback);
        } else {
          return;
        }
      });
    },
    clearOptionForm() {
      this.optionForm = {
        dicTagName: null,
        tagValue: null
      };
      this.$refs.optionForm[0].resetFields();
    },
    subOptions(successCallback, errorCallback) {
      this.optionTableLoading = true
      let form = Object.assign({}, this.currentItem);
      form.factoryId = window.localStorage.factoryId;
      form.dataDicTagList = [].concat(this.optionsList);
      setDataDic(form).then(res => {
        this.$message({
          type: "success",
          message: "操作成功!"
        })
        successCallback()
        this.optionTableLoading = false
      }).catch(err => {
        errorCallback()
        this.optionTableLoading = false
      })
    },
    cancelSaveOptionItem(item) {
      this.$set(item, "isEditing", false);
      this.clearOptionForm();
      if (item.isNewTag === true) {
        this.optionsList.shift();
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.page-box {
  padding: 10px;

  &.box-1 {
    width: 50%;
    margin-right: 20px;
  }

  .options-box {
    border: 1px solid #ddd;

    .options-header {
      height: 50px;
      line-height: 50px;
      font-weight: bold;
      padding: 0 !important;
      margin: 0 !important;
      background: #f5f7fa;
    }

    .option-row {
      padding: 10px 0;

      .show-text {
        line-height: 30px;
      }

      .el-form .el-form-item {
        margin-bottom: 0 !important;
      }
    }
  }
}
</style>
